package com.dingreading.cloud.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.dingreading.cloud.admin.dto.CouponsDto;
import com.dingreading.cloud.admin.dto.StaffDto;
import com.dingreading.cloud.admin.entity.Coupons;
import com.dingreading.cloud.admin.entity.Goods;
import com.dingreading.cloud.admin.entity.GoodsCategory;
import com.dingreading.cloud.admin.service.*;
import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.util.DescribeException;
import com.dingreading.cloud.common.util.PageDto;
import com.dingreading.cloud.common.util.PageUtil;
import com.google.common.collect.HashBasedTable;
import com.mybatisflex.core.paginate.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/coupons")
@Api(tags = "总部-代金券管理")
public class CouponsController {

    @Resource
    private StaffService staffService;
    @Resource
    private CouponsService couponsService;
    @Resource
    private CouponStaffService couponStaffService;
    @Resource
    private GoodsService goodsService;
    @Resource
    protected GoodsCategoryService goodsCategoryService;


    @ApiOperation(value = "分页列表")
    @PostMapping(value = "/pageList")
    public R<Object> pageList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "代金券名") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "分类id") @RequestParam(value = "typeId", required = false) Long typeId,
            @ApiParam(value = "启用状态 1.启用 0.禁用") @RequestParam(value = "enabled", required = false) Integer enabled
    ) {
        Page<CouponsDto> page = this.couponsService.pageList(pageUtil, typeId, keyword, enabled);

        PageDto<CouponsDto> data = new PageDto<>();
        data.setTotal(page.getTotalRow());
        data.setList(page.getRecords());
        return R.ok(data);
    }


    @ApiOperation(value = "根据ID获取信息")
    @PostMapping(value = "/getById", produces = "application/json; charset=UTF-8")
    public R<Object> getById(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id
    ) {
        CouponsDto data = couponsService.dtoById(id);

        boolean send = false;
        long cnt = couponStaffService.getCntByCouponId(id);
        if (cnt > 0) send = true;

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("coupons", data);
        jsonObject.put("send", send);
        return R.ok(jsonObject);
    }


    @ApiOperation(value = "删除")
    @PostMapping(value = "/dropBean", produces = "application/json; charset=UTF-8")
    public R<Object> dropBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id
    ) {
        long cnt = couponStaffService.getCntByCouponId(id);
        if (cnt > 0)
            return R.fail("已发放代金券，不能删除");

        long l = couponsService.dropData(id);
        if (l <= 0) return R.fail("删除失败");

        couponStaffService.dropDataByCouponId(id);
        return R.ok();
    }

    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "新增/修改代金券")
    @PostMapping(value = "/newBean")
    public R<Object> newBean(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id", required = false) Long id,
            @ApiParam(value = "代金券名称") @RequestParam(value = "couponName") String couponName,
            @ApiParam(value = "介绍内容") @RequestParam(value = "intro", required = false) String intro,
            @ApiParam(value = "满足条件的金额") @RequestParam(value = "conformMoney", required = false) Double conformMoney,
            @ApiParam(value = "金额") @RequestParam(value = "couponMoney") Double couponMoney,
            @ApiParam(value = "分类id 1.全额代金券 2.满减代金券 3.商品抵扣券") @RequestParam(value = "typeId") Long typeId,
            @ApiParam(value = "分类名称") @RequestParam(value = "typeName") String typeName,
            @ApiParam(value = "商品id集合") @RequestParam(value = "goodsIds", required = false) String goodsIds,
            @ApiParam(value = "商品分类id集合") @RequestParam(value = "goodsCategoryIds", required = false) String goodsCategoryIds
    ) {
        if (StringUtils.isBlank(couponName))
            return R.fail("请填写代金券名称");
        if (couponMoney == null || couponMoney <= 0)
            return R.fail("代金券金额必须大于0");
        if (typeId == 2 && conformMoney < couponMoney)
            return R.fail("满减金额不能低于代金券金额");
        if (typeId == 3) {
            if (StringUtils.isBlank(goodsIds) && StringUtils.isBlank(goodsCategoryIds)) {
                return R.fail("请选择商品或商品分类");
            }
        }

        if (id == null || id <= 0) {
            // 新增
            Coupons data = new Coupons();
            data.setCouponName(couponName);
            data.setIntro(intro);
            data.setTypeId(typeId);
            data.setTypeName(typeName);
            data.setCouponMoney(couponMoney);
            data.setConformMoney(conformMoney);
            data.setGoodsIds(StringUtils.defaultString(goodsIds));
            data.setGoodsCategoryIds(StringUtils.defaultString(goodsCategoryIds));
            data.setEnabled(1);
            data.setAddStaffUid(headStaffUid);
            data.setAddStaffName(headStaffName);
            couponsService.saveOrUpdate(data);
        } else {
            // 修改
            Coupons data = couponsService.getById(id);
            if (data == null)
                return R.fail("代金券获取失败");
            if (typeId == 3) {
                if (StringUtils.isNotBlank(data.getGoodsIds()) && !data.getGoodsIds().equals(goodsIds)) {
                    String[] goodsIdList = StringUtils.split(data.getGoodsIds(), ",");
                    String[] newGoodsIdList = StringUtils.split(goodsIds, ",");
                    if (newGoodsIdList.length < goodsIdList.length) {
                        return R.fail("新商品不能少于原商品");
                    }
                }
                if (StringUtils.isNotBlank(data.getGoodsCategoryIds()) &&!data.getGoodsCategoryIds().equals(goodsCategoryIds)) {
                    String[] goodsCategoryIdList = StringUtils.split(data.getGoodsCategoryIds(), ",");
                    String[] newGoodsCategoryIdList = StringUtils.split(goodsCategoryIds, ",");
                    if (newGoodsCategoryIdList.length < goodsCategoryIdList.length) {
                        return R.fail("新商品分类不能少于原商品分类");
                    }
                }
            }

            boolean b = couponsService.updateInfo(
                    data.getId(), data.getTypeId(), couponName, intro, goodsIds, goodsCategoryIds, headStaffUid, headStaffName
            );

            if (b) {
                couponStaffService.updateByCouponId(
                        data.getId(), data.getTypeId(), couponName, goodsIds, goodsCategoryIds, headStaffUid, headStaffName
                );
            }
        }

        return R.ok();
    }


    @ApiOperation(value = "更新启用状态")
    @PostMapping(value = "/updateEnabled", produces = "application/json; charset=UTF-8")
    public R<Object> updateEnabled(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "id") @RequestParam(value = "id") Long id,
            @ApiParam(value = "状态 0.禁用 1.启用") @RequestParam(value = "enabled") Integer enabled
    ) {
        boolean l = couponsService.updateEnabled(id, enabled);

        if (!l) return R.fail("更新失败");
        couponStaffService.updateEnabledByCouponId(id, enabled);
        return R.ok();
    }


    @ApiOperation(value = "获取可发送代金券的店长")
    @PostMapping(value = "/getStoreManager", produces = "application/json; charset=UTF-8")
    public R<Object> getStoreManager(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "代金券id") @RequestParam(value = "couponId") Long couponId,
            @ApiParam(value = "门店名/员工名") @RequestParam(value = "keyword", required = false) String keyword
    ) {
        // 获取门店的店长
        PageDto<StaffDto> pageDto = staffService.storeManagerPageList(pageUtil, keyword);
        List<StaffDto> list = pageDto.getList();

        if (CollectionUtils.isNotEmpty(list)) {
            List<String> staffUids = list.stream().map(StaffDto::getStaffUid).collect(Collectors.toList());

            // 获取代金券发放给员工的总数量
            HashBasedTable<String, String, Integer> table = couponStaffService.getStoreStaffSendNum(couponId, 1, staffUids);
            if (!table.isEmpty()) {
                for (StaffDto staffDto : list) {
                    Integer cnt = table.get(staffDto.getStoreUid(), staffDto.getStaffUid());
                    if (null != cnt && cnt > 0)
                        staffDto.setStatus(cnt);
                }
            }
        }

        return R.ok(pageDto);
    }


    @ApiOperation(value = "获取可使用代金券的商品数据")
    @PostMapping(value = "/getGoodsList", produces = "application/json; charset=UTF-8")
    public R<Object> getGoodsList(
            @ApiParam(value = "分页公共类") PageUtil pageUtil,
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName,
            @ApiParam(value = "商品名称") @RequestParam(value = "keyword", required = false) String keyword,
            @ApiParam(value = "商品分类id") @RequestParam(value = "categoryId", required = false) Long categoryId
    ) {
        PageDto<Goods> page = goodsService.pageByCoupon(pageUtil, keyword, categoryId);
        return R.ok(page);
    }

    @ApiOperation(value = "获取可使用代金券的商品分类")
    @PostMapping(value = "/getGoodsCategoryList", produces = "application/json; charset=UTF-8")
    public R<Object> getGoodsCategoryList(
            @ApiParam(value = "总部员工uid") @RequestParam(value = "headStaffUid") String headStaffUid,
            @ApiParam(value = "总部员工名") @RequestParam(value = "headStaffName") String headStaffName
    ) {
        List<GoodsCategory> list = goodsCategoryService.getList();
        return R.ok(list);
    }

}